/*
    Copyright (C) 2025 mio <stigma@disroot.org>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/
#include "playlist.h"

#include <tdeio/global.h>
#include <tdeio/netaccess.h>
#include <tdemessagebox.h>
#include <tdelocale.h>

class PlaylistPrivate
{
public:
    PlaylistPrivate()
        : index(0)
    {
    }

    KURL::List items;
    int index;
};

Playlist::Playlist(TQObject *parent)
	: TQObject(parent)
    , d(new PlaylistPrivate())
{

}

Playlist::~Playlist()
{
    delete d;
}

void Playlist::append(const KURL& mrl)
{
    d->items.append(mrl);
}

void Playlist::append(const KURL::List& items)
{
    for (const KURL& mrl : items) {
        if (mrl.protocol() == "media") {
            TDEIO::UDSEntry e;
            if (!TDEIO::NetAccess::stat(mrl, e, nullptr)) {
                KMessageBox::detailedError(nullptr, i18n("Internal error with the media slave"), TDEIO::NetAccess::lastErrorString());
                continue;
            }
            for (const auto& entry : e) {
                if (entry.m_uds == TDEIO::UDS_LOCAL_PATH && !entry.m_str.isEmpty()) {
                    d->items.append(entry.m_str);
                }
            }
        } else {
            d->items.append(mrl);
        }
    }
}

bool Playlist::isEmpty() const
{
    return d->items.isEmpty();
}

int Playlist::count() const
{
    return d->items.count();
}

int Playlist::currentIndex() const
{
    return d->index;
}

KURL Playlist::currentItem() const
{
    return d->items[d->index];
}

KURL Playlist::at(int index) const
{
    return d->items[index];
}

void Playlist::next()
{
    // Avoid overflow from -1
    if (d->items.isEmpty()) {
        return;
    }

    if (d->index < d->items.count() - 1) {
        ++d->index;
        emit currentIndexChanged(d->index);
        emit currentItemChanged(d->items[d->index]);
    }
}

void Playlist::previous()
{
    if (d->index > 0) {
        --d->index;
        emit currentIndexChanged(d->index);
        emit currentItemChanged(d->items[d->index]);
    }
}

#include "playlist.moc"
